package graphics.screens;

import java.io.IOException;
import java.util.Enumeration;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import playlist.Crawler;
import tool.Path;
import function.Mp3File;
import graphics.CrawlerColor;

public class DeleteNewScreen extends Canvas implements CommandListener {

	private final Command okCommand = new Command("OK", Command.OK, 1);
	private final Command cancelCommand = new Command("Cancel", Command.EXIT, 1);
	private Mp3File mp3;
	
	public DeleteNewScreen(Mp3File aMp3) {
		mp3 = aMp3;
		setup();
	}
	
	public void setup() {
		addCommand(okCommand);
		addCommand(cancelCommand);
		setCommandListener(this);
	}
	
	protected void paint(Graphics graphics) {
		graphics.setColor(CrawlerColor.BLACK);
		graphics.fillRect(0, 0, 240, 250);

		drawSplash(graphics);

		graphics.setColor(CrawlerColor.CRAZY_ORANGE);
		graphics.drawString("Delete tune", 120, (graphics.getFont().getHeight())
				, Graphics.TOP|Graphics.HCENTER);
		graphics.setColor(CrawlerColor.WHITE);
		graphics.drawString(mp3.getTitle(), 120, (graphics.getFont().getHeight()*2)
				, Graphics.TOP|Graphics.HCENTER);
	}

	private void drawSplash(Graphics graphics) {
		try {
			Image splash = Image.createImage("/Musique-mini.png");
			graphics.drawImage(splash, 0, 0, Graphics.LEFT | Graphics.TOP);
		} catch (IOException e) {
			e.printStackTrace();
			Crawler.alert(e);
		}
	}

	public void commandAction(Command command, Displayable disp) {

		if (command == okCommand) {
			int numDeleted = getNumDeleted();
			Crawler.getInstance().deleteCurrentMp3();
		} else if (command == cancelCommand) {
			Crawler.getInstance().readyToGo();
		}
	}

	private int getNumDeleted() {
		int result = 0;
		String newDir = Path.NOW;
		try {
			FileConnection connection = (FileConnection) Connector.open(newDir);
			Enumeration files = connection.list("*.delete", true);
			while (files.hasMoreElements()) {
				files.nextElement();
				result++;
			}
			connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}
